package id.co.shuba.spamobile.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.Configs;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.IDatePickerDialog;
import id.co.shuba.spamobile.IDatePickerTarget;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.R.id;
import id.co.shuba.spamobile.R.layout;
import id.co.shuba.spamobile.R.menu;
import id.co.shuba.spamobile.data.AuditDB;
import id.co.shuba.spamobile.data.DSARDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.HolidayDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.data.ProspectProgressDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.model.AuditInfo;
import id.co.shuba.spamobile.model.DSARInfo;
import id.co.shuba.spamobile.model.ErrorInfo;
import id.co.shuba.spamobile.model.ProspectInfo;
import id.co.shuba.spamobile.model.ProspectProgressInfo;
import id.co.shuba.spamobile.model.SendRefferalInfo;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.util.AuditUtil;
import id.co.shuba.spamobile.util.DialogUtil;
import id.co.shuba.spamobile.util.SpinnerUtil;
import id.co.shuba.spamobile.util.Str;
import id.co.shuba.spamobile.util.ValidationUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.os.Build;

public class FormSendRefferalActivity extends SherlockFragmentActivity implements IDatePickerDialog {
	
	private static final int DATE_DIALOG_ID = 212;
	private static final int TIME_DIALOG_ID = 213;
	private static final String RESULT_APPLICATION = "1001";
	private static final String RESULT_NOT_INTERESTED = "1004";
	private static final String RESULT_REJECTED_BY_UNIT = "1002";
	
	private EditText txtUnitCodeDest;
	private EditText txtUnitName;
	private EditText txtFullName;	
	private Spinner spnJobType;	
	private EditText txtPhone;
	private EditText txtRencanaPlafon;
	private EditText txtAddress;

	private DatabaseHandler _db;
	private DSARDB _dsarDB;
	private StandardDB _optionDB;	
	private ProspectDB _prospectDB;

	private SendRefferalInfo _info;
	private ProspectInfo _prospectInfo;
	private int _visitNo;
	private String _prospectID;
	
	private String defaultOption;	
	
	private MenuItem menuSave;	

	private LogoutReceiver logoutReceiver;
	
	private boolean _ro;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_dsar);
		setUpLogoutReceiver();
		defaultOption = getString(R.string.default_option);
		
		setControls();		

		_db = new DatabaseHandler(this);
		_optionDB = new StandardDB(_db);
		_dsarDB = new DSARDB(_db);
		_prospectDB = new ProspectDB(_db);	
						
		Intent intent = getIntent();		
		_visitNo = -1;
		_prospectID = intent.getStringExtra("prospectID");
		_ro = intent.getBooleanExtra("ro", false);
		_prospectInfo = _prospectDB.getFullInfo(_prospectID);			
		
		/*
		if (intent.hasExtra("visitNo")) {			
			_visitNo = intent.getIntExtra("visitNo", -1);			
			_info = _dsarDB.get(_prospectID, _visitNo);			
			//loadData(_info);
			
			boolean isEditable = isEditable();			
			
			setTitle((isEditable? "Ubah" : "") + "DSAR" + (_ro? " (Read Only)" : ""));
		} else {						
			setTitle("Buat DSAR");
		}
		
		
		Object obj = getLastCustomNonConfigurationInstance();
		if (obj != null) {		
			Object[] states = (Object[])obj;
			//txtDate = (EditText)states[0];
			//txtTime = (EditText)states[1];
		}*/
	}
		

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_form_dsar, menu);

		menuSave = menu.findItem(R.id.menu_save);			
		menuSave.setVisible(isEditable());		
		
        return true;    
	}	
	
	private boolean isEditable() {
		return _info == null || !_ro;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Send")) {			
			send();
		}
		
	    return super.onOptionsItemSelected(item);
	}	
	
	private void setControls() {
		txtUnitCodeDest = (EditText) findViewById(R.id.txtUnitCodeDest);
		txtUnitName = (EditText) findViewById(R.id.txtUnitName);
		txtFullName = (EditText) findViewById(R.id.txtFullName);
		spnJobType = (Spinner) findViewById(R.id.spnJobType);
		
		txtPhone = (EditText) findViewById(R.id.txtPhone);
		txtRencanaPlafon = (EditText) findViewById(R.id.txtRencanaPlafon);
		txtAddress = (EditText) findViewById(R.id.txtAddress);				
	}	
	
	private SendRefferalInfo getData() {
		UserInfo userInfo = Sessions.getUser(this);
		return getData(userInfo);
	}
	
	private SendRefferalInfo getData(UserInfo user) {
		SendRefferalInfo info = new SendRefferalInfo();		
		info.setUnitCodeTo(txtUnitCodeDest.getText().toString());					
		
		info.setFullName(txtFullName.getText().toString());		
		info.setJobType(SpinnerUtil.optionGetSelectedValue(spnJobType, defaultOption));
		info.setPhone(txtPhone.getText().toString());
		try {
			info.setPlafon(Long.parseLong(txtRencanaPlafon.getText().toString()));
		} catch (Exception e) {		
		}		
		info.setAlamat(txtAddress.getText().toString());
				
		//info.setTimeVisitActual(time);
		
		String date = App.getProcessDateTime();
				
		if (_info == null) {
			info.setEntryBy(user.getNip());
			info.setEntryDate(date);
		} else {
			info.setEntryBy(_info.getEntryBy());
			info.setEntryDate(_info.getEntryDate());
		}	
		
		info.setUpdateBy(user.getNip());
		info.setUpdateDate(date);
		
		//info.setIsUpload("0");
		
		return info;
	}

	/*
	public void onDateDialogButtonClick(View v) {
		switch (v.getId()) {
		case R.id.btnPickVisitPlanDate:
			txtDate = txtVisitPlanDate;
			break;
		case R.id.btnPickVisitActualDate:
			txtDate = txtVisitActualDate;
			break;
		}
		showDialog(DATE_DIALOG_ID);
	}
	
	public void onTimeDialogButtonClick(View v) {
		switch (v.getId()) {
		case R.id.btnPickVisitPlanTime:
			txtTime = txtVisitPlanTime;
			break;
		case R.id.btnPickVisitActualTime:
			txtTime = txtVisitActualTime;
			break;
		}		
		showDialog(TIME_DIALOG_ID);		
	}
		
	
	@Override	
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return DialogUtil.create(this, txtDate);
		case TIME_DIALOG_ID:
			return DialogUtil.createTimePicker(this, txtTime);
		}

		return null;
	}*/	
	
	private List<ErrorInfo> validate(SendRefferalInfo info) {
	
		List<ErrorInfo> errors = new ArrayList<ErrorInfo>();
		/*if (!DialogUtil.isValid(info.getDateVisitPlan()))
			errors.add(new ErrorInfo(txtVisitPlanDate, getString(R.string.visit_plan)));*/
		/*
		if (_info == null && !DialogUtil.isValidAfterward(info.getDateVisitPlan()))
			errors.add(new ErrorInfo(txtUnitCodeDest, getString(R.string.unit_code_dest), "Tanggal rencana kunjungan tidak boleh kurang dari tanggal sekarang"));
		
		if (_info != null) {
			if (!DialogUtil.isValid(info.getDateVisitActual()))
				errors.add(new ErrorInfo(txtVisitActualDate, getString(R.string.visit_actual_date)));			
			/*if (!DialogUtil.isValidAfterward(info.getDateVisitActual(), info.getDateVisitPlan()))
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date) + " < "
				+ getString(R.string.visit_plan)));			
			if (!DialogUtil.isValidAfterward(info.getDateVisitActual(), info.getDateVisitPlan())) {
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date), "Tanggal kunjungan aktual harus lebih besar dari tanggal rencana kunjungan"));
			} else if (!DialogUtil.isValidAfterward(App.getProcessDate(), info.getDateVisitActual())) {
				errors.add(new ErrorInfo(txtVisitActualDate,
						getString(R.string.visit_actual_date), "Tanggal kunjungan aktual tidak boleh lebih dari tanggal sekarang"));
			}
			if (!"".equals(info.getTimeVisitActual()) && !DialogUtil.isValidTime(info.getTimeVisitActual()))
				errors.add(new ErrorInfo(txtVisitActualTime, getString(R.string.visit_actual_time)));				
			if (info.getObjectiveOfVisit() == null)
				errors.add(new ErrorInfo(spnPurpose, getString(R.string.purpose)));			
			if (info.getResultOfVisit() == null)
				errors.add(new ErrorInfo(spnResult, getString(R.string.result)));						
			if (RESULT_NOT_INTERESTED.equals(info.getResultOfVisit()) && info.getRemark() == null)
				errors.add(new ErrorInfo(spnReason, getString(R.string.reason)));
			if (Str.isNullOrEmpty(info.getRemark()))
				errors.add(new ErrorInfo(txtRemark, "Catatan Kunjungan"));
			
			if (info.getRemark().length() > 255)
				errors.add(new ErrorInfo(txtRemark, "Catatan Kunjungan", "Catatan Kunjungan maksimal 255 karakter"));
		}
		*/
		return errors;
	}				

	private void send() {				
		final UserInfo user = Sessions.getUser(this);
		final SendRefferalInfo info = getData(user);			
		
		List<ErrorInfo> errors = validate(info);						
		
		if (errors.size() > 0) {																																			
			ValidationUtil.showValidationDialog(this, errors, this);
			return;
		}			
		
		addTransactionLog("INSERT", info);
		setResult(Activity.RESULT_OK);
		finish();
	}		
	
	private void addTransactionLog(String actType, SendRefferalInfo info) {
		TransactionLogDB trans = new TransactionLogDB(_db);
		String primaryKey = "N/A";
		try {
			primaryKey = AuditUtil.getPrimaryKeyInfo(info);
		} catch (Exception e) {			
		}		
		trans.add(info.getUpdateBy(), actType, String.format("%s %s", actType, primaryKey));
	}
	
	
	
	
		
	/*
    public void showDateDialog(EditText dateDisplay, Calendar date) {
        activeDateDisplay = dateDisplay;
        activeDate = date;
        showDialog(DATE_DIALOG_ID);
    }*/  
	
	@Override
	public void onBackPressed() {
		if (_ro) {
			finish();
			return;
		}	
		
		SendRefferalInfo info = getData();
		boolean isChanged = false;
		try {
			isChanged = _info == null?
					AuditUtil.isFormChanged(SendRefferalInfo.class, _info, info, defaultOption, "DATE_VISIT_PLAN"):
					AuditUtil.isFormChanged(SendRefferalInfo.class, _info, info, defaultOption);
		} catch (Exception e) {		
			e.printStackTrace();
		}	
		
		if (!isChanged) {
			finish();
			return;
		}			
							
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.confirm)
        .setMessage(R.string.save_changes)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {           
            	dialog.dismiss();
                    
            }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                finish();    
            }
        })
        .show();      
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();			
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}

	@Override
	public void show(EditText txt) {
		// TODO Auto-generated method stub
		
	}
	
}